<template>
    <div>

        <div class="user">


            <div class="header">
                <el-input type="text" v-model="keyword" placeholder="请输入内容" @change="toSearch"></el-input>
                <el-button type="primary" @click="toSearch">搜索</el-button>
                <el-button type="primary" @click="addDialog">添加用户</el-button>
                <UserDialog ref="userdialog" />
            </div>
            <div class="goods_table">
                <el-table ref="userTable" :data="userData" tooltip-effect="dark" style="width: 100%"
                    @selection-change="handleSelectionChange" @select="selectionRow" v-loading="loading" border>
                    <el-table-column type="selection" width="55">
                    </el-table-column>
                    <el-table-column prop="id" label="用户ID" width="120">
                    </el-table-column>
                    <el-table-column prop="username" label="用户名称" width="120">
                    </el-table-column>
                    <el-table-column prop="phone" label="电话" width="120">
                    </el-table-column>
                    <el-table-column prop="email" label="邮箱" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column prop="address" label="地址" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column prop="birth" label="出生日期" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column prop="create_time" label="创建日期" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column prop="editor_time" label="修改日期" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column prop="name" label="操作" show-overflow-tooltip>
                        <template slot-scope="scope">
                            <el-button size="mini" icon="el-icon-edit" type="primary"
                                @click="usersEditor(scope.$index, scope.row)">编辑</el-button>
                            <el-button size="mini" icon="el-icon-delete" type="danger"
                                @click="usersDelete(scope.$index, scope.row)">删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div style="margin-top: 20px">
                    <el-button @click="toggleSelection()" type="primary">取消选择</el-button>
                    <el-button @click="lotCancel" type="primary">批量删除</el-button>
                </div>
            </div>
            <MyPage :total="total" :pageSize="pageSize" :currentPage="currentPage" @changePageNum="getPageNum" />
        </div>
    </div>

</template>

<script>
import UserDialog from './UserDialog.vue';
import MyPage from '@/components/Mypage.vue'



export default {
    data() {
        return {
            loading:false,
            keyword: '',
            userData: [],
            multipleSelection: [],
            getUsersList: [],
            searchList: [],
            isSelect: false,
            total: 10,
            pageSize: 10,
            currentPage: 1,
            type: 2  //2:查询所有商品分页  1:查询搜索列表的分页
        };
    },
    components: {
        UserDialog,
        MyPage,

    },
    created() {
        let that = this;
        let temp = localStorage.getItem('user_currentPage')
        let temp_type = localStorage.getItem('user_type')
        if (temp_type == 1) {
            this.keyword = localStorage.getItem('user_keyword');
            this.toSearch()
        } else {
            if (temp) {
                this.currentPage = temp;
            }
            that.$nextTick(function () {
                this.getUser()
            }, 200)
        }
    },
    methods: {
        getUser() {
            this.loading=true;
            this.$ajax({
                method: 'get',
                url: '/api/getUsers',
            }).then(res => {
                console.log('res:', res)
                let data = res.data.data
                this.getUsersList = data,
                    this.userData = this.getUsersList.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
                this.total = data.length;
                if (this.total > 0 && this.userData.length == 0) {
                    this.currentPage--;
                    localStorage.setItem('user_currentPage', this.currentPage);
                    this.userData = this.getUsersList.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
                }
                this.loading=false;
            }).catch(function (err) {
                console.log(err)
            })
        },
        toSearch() {
            if (this.keyword) {
                console.log("type=1")
                this.type = 1;
            } else {
                console.log("type=2")
                this.type = 2;
                this.getUser()
            }
            localStorage.setItem('user_type', this.type);
            localStorage.setItem('user_keyword', this.keyword)

            this.$ajax({
                method: 'get',
                url: '/api/users_search',
                params: { search_word: this.keyword }
            }).then(res => {

                let data = res.data.result
                this.searchList = data;
                this.currentPage = 1;
                this.userData = this.searchList.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
                this.total = data.length;
                if (this.total > 0 && this.userData.length == 0) {
                    this.currentPage--;
                    localStorage.setItem('user_currentPage', this.currentPage);
                    this.userData = this.searchList.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
                }
            }).catch(function (err) {
                console.log(err)
            })

        },
        toggleSelection(rows) {
            if (rows) {
                rows.forEach(row => {
                    this.$refs.userTable.toggleRowSelection(row);
                });
            }
            else {
                this.$refs.userTable.clearSelection();
            }
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        addDialog() {
            this.$refs.userdialog.dialogFormVisible = true;
            this.$refs.userdialog.title = '添加用户'
        },
        handleCheck(index, row) {
            console.log(index, row);
        },
        usersEditor(index, row) {
            this.$refs.userdialog.dialogFormVisible = true;
            this.$refs.userdialog.title = '编辑用户';
            localStorage.setItem('usersMessage', JSON.stringify(row))
            localStorage.setItem('user_currentPage', this.currentPage)
        },
        usersDelete(index, row) {
            let temp = this.$refs.userTable.selection;
            temp.forEach(el => {
                if (el.id == row.id) {
                    this.isSelect = true;
                    this.$ajax({
                        method: 'post',
                        url: '/api/users_delete',
                        params: { users_id: row.id }
                    }).then(res => {
                        console.log("data:", res)
                        this.$message({
                            message: '删除用户成功！',
                            type: 'success'
                        });
                        localStorage.setItem('user_currentPage', this.currentPage)
                        this.reload()
                    }).catch(function (err) {
                        console.log(err)
                        this.$message({
                            message: '删除用户失败！',
                            type: 'error'
                        });
                    })
                }
            });
            if (!this.isSelect) {
                this.$message({
                    message: '请选中后再删除！',
                    type: 'warning'
                })
                this.isSelect = false;
            }
        },
        lotCancel() {
            let temp = this.$refs.userTable.selection
            let cancelSelect = JSON.stringify(temp)
            console.log('选中的有：', cancelSelect)
            if (temp.length > 0) {
                this.$ajax({
                    method: 'post',
                    url: '/api/users_deleteSelect',
                    params: { data: cancelSelect }
                }).then(res => {
                    console.log("data:", res)
                    this.$message({
                        message: '删除用户成功！',
                        type: 'success'
                    });
                    localStorage.setItem('user_currentPage', this.currentPage)
                    this.reload()
                }).catch(function (err) {
                    console.log(err)
                    this.$message({
                        message: '删除用户失败！',
                        type: 'error'
                    });
                })
            } else {
                this.$message({
                    message: '请选择用户！',
                    type: 'warning'
                });
            }

        },
        getPageNum(page) {
            this.currentPage = page
            localStorage.setItem('user_currentPage', this.currentPage)
            console.log("用户列表：", this.getUsersList)
            if (this.type == 1) {
                this.userData = this.searchList.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
            } else {
                this.userData = this.getUsersList.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
            }

        }
    },
    inject: ['reload']
}
</script>

<style lang="less" scoped>
.user {
    padding: 20px;


    .header {
        display: flex;
        margin-bottom: 20px;

        button {
            margin-left: 20px;
        }
    }


    // .goods_page {
    //     margin: 20px auto;
    //     align-content: center;
    //     position: absolute;
    //     left:50%;
    //     top:100%;
    //     transform: translate(-50%,-50%);
    // }
}
</style>